var queues = require('mysql-queues');
const DEBUG = true;
var selectUserRole = function(connection, callback) {
	var sql = 'select * from user_role';
	connection.query(sql, function(err, rows) {
		if (err){
			console.log(err);
            console.log(err.stack);
		}
		callback(rows);
		connection.release();
	});
},
	addUserRole = function(connection, data, callback) {
		queues(connection, DEBUG);
		var sql = 'insert into user_role(userId,roleId) values(?,?)';
		var trans = connection.startTransaction(); 
		trans.query(sql, [data.userId, data.roleId], function(err, rows) {
			if (err) {
				console.log(err);
				console.log(err.stack);
				trans.rollback();
			} else {
				trans.commit(function(err, info) {
					console.log(info);
				});
			}
			callback(rows);
		});
		trans.execute();
		console.log('execute addUserRole');
		connection.release();
	},
	deleteUserRole = function(connection, id, callback) {
		queues(connection, DEBUG);
		var sql = 'delete from user_role where id=?';
		var trans = connection.startTransaction();
		trans.query(sql, id, function(err, rows) {
			if (err) {
				console.log(err);
				console.log(err.stack);
				trans.rollback();
			} else {
				trans.commit(function(err, info) {
					console.log(info);
				});
			}
			console.log('rows', rows);
			callback(rows);
		});
		trans.execute();
		console.log('execute');
		connection.release();
	},
	updateUserRole = function(connection, data, callback) {
		queues(connection, DEBUG);
		var sql = 'update user_role set userId=?,roleId=? where id=?';
		var trans = connection.startTransaction();
		trans.query(sql, [data.userId, data.roleId, data.id], function(err, rows) {
			if (err) {
				console.log(err);
				console.log(err.stack);
				trans.rollback();
			} else {
				trans.commit(function(err, info) {
					console.log('info:', info);
				});
			}
			console.log('rows', rows);
			callback(rows);
		});
		trans.execute();
		console.log('execute update');
		connection.release();
	},
	findById = function(connection, id, callback) {
		var sql = 'select * from user_role where id=?';
		connection.query(sql, id, function(err, rows) {
			callback(rows);
			connection.release();
		});
	};

	findRoleNameByUid = function(connection, uid, callback){
		var sql = 'select r.roleName from user_role ur, role r where ur.roleId=r.id and ur.userId=?';
		connection.query(sql, uid, function(err,rows){
			callback(rows);
			connection.release();
		});
	}

module.exports = {
	selectUserRole: selectUserRole,
	addUserRole: addUserRole,
	deleteUserRole: deleteUserRole,
	updateUserRole: updateUserRole,
	findById: findById,
	findRoleNameByUid: findRoleNameByUid
};